﻿using System;

namespace Searches
{
    public class BinarySearch
    {
        public int IndexOf(int[] sortedArray, int element)
        {
            int start = 0;
            int end = sortedArray.Length;
            while (start < end)
            {
                int middle = (end + start)/2;

                if(element == sortedArray[middle])
                {
                    return middle;
                }
                if (element > sortedArray[middle])
                {
                    start = middle;
                }
                else
                {
                    end = middle;
                }

                if((end - start) == 1 && (end == middle || start == middle))
                {
                    break;
                }
            }

            return -1;
        }

        public int IndexOf(int[] sortedArray, int v, int l, int r)
        {
            while (r >= 1)
            {
                int m = (l + r)/2;
                if (v == sortedArray[m])
                    return m;
                if (v < sortedArray[m])
                    r = m - 1;
                else
                    l = m + 1;
            }

            return -1;
        }
    }
}